use serde::{Deserialize, Serialize};
use tauri::{command, AppHandle, Manager, Window};

// 会议配置
#[derive(Debug, Serialize, Deserialize)]
pub struct JitsiConfig {
    pub room_name: String,
    pub server_url: String,
    pub display_name: Option<String>,
    pub audio_muted: bool,
    pub video_muted: bool,
}

// 初始化 Jitsi 会议
#[command]
pub async fn init_jitsi(window: Window, config: JitsiConfig) -> Result<(), String> {
    // 1. 请求媒体设备权限
    let has_permissions = request_media_permissions(&window).await?;
    if !has_permissions {
        return Err("用户拒绝了媒体设备权限".into());
    }

    // 2. 通知前端可以创建 Jitsi 实例
    window
        .emit("jitsi-permissions-granted", config)
        .map_err(|e| e.to_string())?;

    Ok(())
}

// 请求摄像头和麦克风权限
async fn request_media_permissions(window: &Window) -> Result<bool, String> {
    #[cfg(target_os = "macos")]
    {
        // macOS 需要特殊处理权限
        use tauri::api::dialog::blocking::ask;
        use tauri::api::os::macos::{Authorization, AuthorizationFlags, AuthorizationRights};

        let auth = Authorization::new()
            .flags(AuthorizationFlags::USER_INTERACTION_ALLOWED)
            .rights(AuthorizationRights::new())
            .build()
            .map_err(|e| format!("权限授权失败: {}", e))?;

        let granted = auth
            .authorize()
            .await
            .map(|_| true)
            .unwrap_or_else(|_| false);

        if !granted {
            ask(
                Some(&window.app_handle()),
                "权限请求",
                "需要摄像头和麦克风权限才能进行视频会议",
            );
        }

        Ok(granted)
    }

    #[cfg(not(target_os = "macos"))]
    {
        // 其他平台假设已通过 manifest 声明权限
        Ok(true)
    }
}

// 清理资源
#[command]
pub fn dispose_jitsi(window: Window) -> Result<(), String> {
    window
        .emit("jitsi-dispose", ())
        .map_err(|e| e.to_string())?;
    Ok(())
}
